﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Common.Logging;
using System.Reflection;

namespace DotNetNexusSpam
{
    public class EmailUtil
    {
        private static ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// Checks if the email has a valid format.
        /// </summary>
        private static string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
                                     @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
                                     @".)+))([a-zA-Z]{2,6}|[0-9]{1,6})(\]?)$";

        public static bool IsValidEmail(string email)
        {
            Regex re = new Regex(strRegex);
            if (re.IsMatch(email))
                return (true);
            else
                return (false);
        }

        /// <summary>
        /// Tries to convert the email in a valid email removing noise.
        /// </summary>
        public static string ConvertToValidEmail(string email)
        {
            string emailConverted = "";
            if (email.Contains("<") && email.Contains(">"))
                try
                {
                    emailConverted = email.Substring(email.IndexOf("<") + 1, (email.IndexOf(">") - email.IndexOf("<") - 1));
                }
                catch (Exception formatExcp)
                {
                    _log.Error(String.Format("The email is not valid: {0}", formatExcp));
                }
            else
            {
                if (email.StartsWith("<"))
                    emailConverted = email.Substring(email.IndexOf("<") + 1, email.Length);
                if (email.EndsWith(">"))
                    emailConverted = email.Substring(0, email.IndexOf(">") - 1);
            }
            return emailConverted;
        }

        /// <summary>
        /// Tries to extract the email's domain.
        /// </summary>
        public static string DomainFromEmail(string email)
        {
            string domain = "";
            if (email.Contains("@"))
                domain = email.Substring(email.IndexOf("@") + 1, email.Length - email.IndexOf("@") - 1);
            return domain;
        }
    }
}
